package com.ikun.admin.modules.auth.service;

import com.ikun.admin.modules.auth.constant.SecurityConstant;
import com.ikun.admin.modules.auth.utils.ResponseUtils;
import com.ikun.admin.modules.auth.utils.SecurityUtil;
import com.ikun.common.constant.RedisConstant;
import com.ikun.common.manager.RedisManager;
import com.ikun.common.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName LoginOutService
 * @Description: 退出处理接口
 * @CreateDate: 2024/7/11 11:45
 */
@Service
public class LoginOutService implements LogoutHandler {
    @Autowired
    private RedisManager redisManager;

    @Autowired
    private TokenAboutRedisService tokenAboutRedisService;

    @Value("${starters.jwt.token-key}")
    private String tokenKey;

    @Override
    public void logout(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) {
        //拿到token删除权限和角色信息返回退出成功
        String token = req.getHeader(tokenKey);

        //删除token相关信息
        tokenAboutRedisService.removeAboutToken(RedisConstant.USER_ID_PREFIX,token);
        tokenAboutRedisService.removeAboutToken(RedisConstant.USER_PERM_PREFIX,token);
        //删除登录状态
        Long id = SecurityUtil.getCurrentUserId();
        tokenAboutRedisService.removeAboutToken(RedisConstant.ONLINE_USER_SET,String.valueOf(id));

        try {
            ResponseUtils.sendResponse(resp, new Result().success());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
